<template>
    <div class="chat-layout">
        <!-- 左侧联系人列表 -->
        <div class="sidebar">
            <div class="search-bar">
                <input v-model="searchKeyword" placeholder="搜索联系人" class="search-input" />
                <i class="search-icon">🔍</i>
            </div>

            <!-- 消息联系人 -->
            <el-card class="history-contacts">
                <div v-for="item in historyContacts" :key="item.id" class="contact-item"
                    @click="selectContactById(item)">
                    <div class="avatar-container">
                        <el-avatar :size="40" :src="item.userRelatedMessageResp?.avatar || 'default-avatar-url.png'"
                            class="avatar"></el-avatar>
                        <span class="status-dot"
                            :style="{ backgroundColor: onlineUser.includes(String(item.id)) ? '#41968d' : '#CCCCCC' }"></span>

                    </div>
                    <div class="contact-info">
                        <div>
                            <span class="contact-name">{{ item.userRelatedMessageResp?.name || '未设置姓名' }}</span>
                            <span class="contact-company"><i class="el-icon-office-building"></i>{{
                                item.userRelatedMessageResp?.companyName || '未设置公司' }}</span>
                        </div>
                        <div class="contact-last-message">{{ truncateText(item.lastMessage) }}</div>
                    </div>
                    <div class="contact-meta">
                        <div class="contact-time">{{ formatTime(item.lastMessageTime) }}</div>
                        <!-- 显示未读消息数量 -->
                        <!-- <span v-if="item.unreadCount > 0" class="unread-badge">
                            {{ item.unreadCount }}
                        </span> -->
                    </div>
                </div>
            </el-card>


            <div class="empty" v-if="!offlineContacts.length && !historyContacts.length">
                暂无联系人
            </div>
        </div>

        <!-- 右侧聊天窗口（子组件） -->
        <div class="chat-window-container">
            <ChatWindow v-if="selected && userType" :messages="selectedContact.messages" :toUserId="selectedContact.id"
                :userType="userType" :userRelatedMessageResp="selectedContact.userRelatedMessageResp"
                @sendMessage="sendMessage" />
            <div v-else class="empty-chat">
                请选择一个联系人开始聊天
            </div>
        </div>
    </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
import ChatWindow from './ChatWindow.vue';

export default {
    name: 'WebSocketChat',
    components: { ChatWindow },
    props: {
        userType: {
            type: String,
            default: 'seeker',
            required: true
        }
    },
    data() {
        return {
            searchKeyword: '',
            selected: false,
            selectedContact: null,
            onlineUser: [],

        };
    },
    computed: {
        ...mapState('chat', [
            'wsState',
            'offlineContacts',
            'historyContacts',
            'recruiterOnlineUsers',
            'seekerOnlineUsers'

        ]),
        ...mapGetters('chat', [
            'connectionStatus',
            'currentContactMessages',
            'filteredOfflineContacts',
            'filteredHistoryContacts'
        ]),
    },
    methods: {
        selectContactById(item) {
            this.selectedContact = item
            this.selected = true;
        },

        // 发送消息
        async sendMessage(content, toUserId) {
            if (!content) return;

            try {
                if (this.userType === 'seeker') {
                    await this.$store.dispatch('chat/sendChatMessage', {
                        toUserId,
                        fromRole: "seeker",
                        content,
                        toRole: "recruiter"
                    });
                } else {
                    await this.$store.dispatch('chat/sendChatMessage', {
                        toUserId,
                        fromRole: "recruiter",
                        content,
                        toRole: "seeker"
                    });
                }
                // 关键：更新 selectedContact 引用以触发重新渲染
                const contactIndex = this.historyContacts.findIndex(
                    item => item.id === toUserId
                );

                if (contactIndex !== -1) {
                    this.selectedContact = { ...this.historyContacts[contactIndex] };
                }
            } catch (error) {
                console.error('发送消息失败:', error);
            }


        },

        // 工具方法
        formatTime(timeStr) {
            if (!timeStr) return '';

            const now = new Date();
            const target = new Date(timeStr);

            // 计算时间差（毫秒）
            const diffMs = now - target;
            // 计算天数差
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
            // 计算年数差
            const diffYears = now.getFullYear() - target.getFullYear();

            // 格式化函数
            const formatMonthDay = () => {
                const month = target.getMonth() + 1;
                const day = target.getDate();
                return `${month}月${day}日`;
            };

            const formatFullDate = () => {
                const year = target.getFullYear();
                const month = target.getMonth() + 1;
                const day = target.getDate();
                return `${year}年${month}月${day}日`;
            };

            const formatTime = () => {
                const hours = String(target.getHours()).padStart(2, '0');
                const minutes = String(target.getMinutes()).padStart(2, '0');
                return `${hours}:${minutes}`;
            };

            // 根据时间间隔返回不同格式
            if (diffDays < 1) {
                return formatTime(); // 一天内：显示时分
            } else if (diffYears < 1) {
                return formatMonthDay(); // 一年内：显示月日
            } else {
                return formatFullDate(); // 超过一年：显示年月日
            }
        },

        truncateText(text, length = 14) {
            if (!text) return '';
            return text.length > length
                ? text.substring(0, length) + '...'
                : text;
        },

        // 统一同步逻辑
        syncOnlineUser() {
            this.onlineUser = this.userType === 'seeker'
                ? this.recruiterOnlineUsers
                : this.seekerOnlineUsers;

            console.log("看一看在线用户", this.onlineUser);

        }
    },
    created() {
        // 初始化时根据 userType 赋值
        this.syncOnlineUser();
    },
    watch: {
        // 监听当前用户类型对应的状态数组变化
        recruiterOnlineUsers: {
            handler() {
                if (this.userType === 'seeker') {
                    this.syncOnlineUser();
                }
            },
            deep: true // 关键：如果数组内元素变化（如新增/删除id），需深度监听
        },
        seekerOnlineUsers: {
            handler() {
                if (this.userType !== 'seeker') {
                    this.syncOnlineUser();
                }
            },
            deep: true // 深度监听数组内部变化
        }
    },
};
</script>

<style scoped>
/* 保持原有样式不变 */
.chat-layout {
    display: flex;
    height: 100%;
    overflow: hidden;
}

/* 搜索栏固定在顶部 */
/* .search-bar {
    padding: 12px;
    border-bottom: 1px solid #eee;
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
    
} */

/* 联系人列表容器：固定高度，启用滚动 */
.history-contacts {
    height: calc(100vh - 60px);
    /* 减去搜索栏高度，剩下的空间用于列表 */
    overflow-y: auto;
    /* 仅在内容超出时显示垂直滚动条 */
    padding: 0;
    /* 清除卡片内边距 */
    border: none;
    /* 清除卡片边框 */
}

/* 隐藏滚动条（保留滚动功能） */
.history-contacts::-webkit-scrollbar {
    width: 4px;
    /* 滚动条宽度 */
}

.history-contacts::-webkit-scrollbar-track {
    background: transparent;
    /* 滚动条轨道透明 */
}

.history-contacts::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.3);
    /* 滚动条颜色（半透明） */
    border-radius: 2px;
    /* 滚动条圆角 */
}

/* 鼠标悬停时让滚动条更明显 */
.history-contacts:hover::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.6);
}

.sidebar {
    width: 33%;
    margin-right: 5px;
    background: #eee;
    border-radius: 8px;
    height: 80vh;
    /* 全屏高度 */
    overflow: hidden;
    /* 隐藏容器自身的滚动条 */
    border-right: 1px solid #eee;
    /* 可选：添加分隔线 */
}

.contact-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
}

.contact-item:hover {
    background-color: #eee;
}

.unread-badge {
    background-color: #ff4d4f;
    color: #eee;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
}

.search-input {
    width: 94%;
    padding: 10px;
    border: 1px solid #eee;
    box-sizing: border-box;
}

.search-icon {
    background-color: #eee;
}

.avatar-container {
    position: relative;
    /* 关键：作为子元素的定位容器 */
    display: inline-block;
    /* 避免容器宽度占满父元素 */
}

.status-dot {
    position: absolute;
    bottom: 0;
    /* 距离底部0px */
    right: 0;
    /* 距离右侧0px */
    width: 12px;
    /* 圆点大小 */
    height: 12px;
    border-radius: 50%;
    /* 圆形 */
    border: 2px solid #fff;
    /* 白色边框，避免与头像边缘融合 */
}

.contact-name {
    font-size: 16px;
    margin-right: 10px;
}

.contact-company {
    font-size: 14px;
    color: #757373;
}

.contact-last-message {
    font-size: 14px;
    color: #757373;
    text-align: left;
}

.chat-window-container {
    flex: 1;
    overflow: hidden;
}

/* 其他样式保持不变 */
</style>